import time
import hashlib



AllUsers = {}
Rooms = []
from .room import Room

class User:
    def __init__(self, ws, userAgent):
        self.ws = ws
        self.userAgent = userAgent
        self.setName()
        self.room = None  # 加入的房间
        self.chessBoard = None  # 在线棋盘

    def setName(self):
        h = hashlib.sha256(f'{time.time()}'.encode())
        self.name = '访客' + h.hexdigest()[:12]

    def login(self, **kwargs):
        res = {
            "name": self.name,
            "chessBoard": True if self.chessBoard else False
        }
        self.ws.send(kwargs.get('func'), res)

    # 获取大厅房间
    def getRoom(self, **kwargs):
        # i = kwargs.get('index',0)
        res = {
            "rooms": [room.toJson() for room in Rooms],  # [i:i+10]
            "maxRoom": len(Rooms)
        }
        self.ws.send(kwargs.get('func'), res)

    # 设置棋盘
    def setChess(self,chess):
        self.chessBoard = chess

    # 创建房间
    def createRoom(self, **kwargs):
        if self.room:
            return self.ws.send(kwargs.get('func'), {"code": -1, "mes": "你已创建了一个房间"})
        self.room = Room(self)
        self.room.setName(kwargs.get('name'))
        Rooms.append(self.room)
        res = {
            "code": 0,
            "room": self.room.toJson()
        }
        self.ws.send(kwargs.get('func'), res)

    # 删除自己建房间
    def delRoom(self, **kwargs):
        if not self.room:
            return self.ws.send(kwargs.get('func'), {"code": -1, "mes": "无效房间"})
        Rooms.remove(self.room)
        self.room = None
        self.ws.send(kwargs.get('func'), {})

    # 加入房间
    def joinRoom(self, **kwargs):
        roomName = kwargs.get('name')
        room = None
        for rm in Rooms:
            if rm.getName() == roomName:
                room = rm
        if not room:
            return self.ws.send(kwargs.get('func'), {"code": -1, "mes": "房间不存在"})
        if room.getManage() == self.name:
            return self.ws.send(kwargs.get('func'), {"code": -1, "mes": "无法加入自己创建的房间"})

        if room.isFull():
            return self.ws.send(kwargs.get('func'), {"code": -1, "mes": "房间已满"})
        room.join(self)
